package apps.reading.spider;

import java.util.ArrayList;
import java.util.List;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;

import apps.reading.ReadingSpider;
import apps.reading.WebSourceParser;
import apps.reading.db.WebSourceBean;
import core.tool.common.StringHelper;
import core.tool.htmlparser.HtmlparserUtil;

@ReadingSpider(sourceType="0", type="1", url = "http://www.cnblogs.com/aggsite/topviews")
public class CnBolgs48Top implements WebSourceParser {

	public WebSourceBean getContent(WebSourceBean webSourceBean) {
		String content=HtmlparserUtil.getNodeStr(webSourceBean.getContentURL(), "div", "id", "cnblogs_post_body",true);
		webSourceBean.setContent(content);
		return webSourceBean;
	}

	public List<WebSourceBean> getWebSourceTitleList(String url) {
		List<WebSourceBean> webSourceList=new ArrayList<WebSourceBean>();
        Node[] nodes = HtmlparserUtil.getNodeList(url, "div", "class", "post_item_body");
        String line = "";
        for (int i = 0; i < nodes.length; i++) {
            Node node = nodes[i];
  		  	String result=node.toHtml();
            webSourceList.add(getWebSourceBeanOfStr(result));
        }		
		return webSourceList;		
	}
	
	/**
	 * @param result
	 * @return
	 */
	private WebSourceBean getWebSourceBeanOfStr(String result) {
		WebSourceBean webSourceBean=new WebSourceBean();
		webSourceBean.setId(StringHelper.getUUID());
		webSourceBean.setType(WebSourceBean.TYPE_NEWS_TOPVIEWS);
		webSourceBean.setSourceType(WebSourceBean.SOURCE_TYPE_CNBLOG);
		try {
			Parser parser = new Parser();
			parser.setInputHTML(result);
			NodeFilter filter = new TagNameFilter("A");
			NodeList nodelist = parser.parse(filter);
			for (int i = 0; i < nodelist.size(); i++) {
				Node node = nodelist.elementAt(i);
				LinkTag link = (LinkTag) nodelist.elementAt(i);
				if (i == 0) {
					webSourceBean.setContentURL(link.getAttribute("href"));
					webSourceBean.setTitle((link.getStringText()));
				}
				if (i == 1) {
					webSourceBean.setAuthor(link.getStringText());
				}
			}
			filter = new TagNameFilter("p");
			nodelist = parser.parse(filter);
			for (int i = 0; i < nodelist.size(); i++) {
				Node node = nodelist.elementAt(i);
				if (i == 0) {
					webSourceBean.setRemark(node.getText());
				}
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return webSourceBean;
	}	

}
